package org.example.controller;


import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;
import org.example.entity.News;
import org.example.entity.NewsSaveEntity;
import org.example.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.solr.core.SolrTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author guocb
 * @since 2021-03-06
 */
@Controller
@RequestMapping("/news")
public class NewsController {

    @Autowired
    INewsService newsService;

    @Autowired
    SolrTemplate solrTemplate;

    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("newsList", newsService.list());
        return "newslist";
    }

    @GetMapping("/del")
    public String del(Integer nid) {
        if (newsService.removeById(nid)) {
            solrTemplate.deleteByIds("news_core", nid.toString());
            solrTemplate.commit("news_core");
        }
        return "redirect:list";
    }

    @RequestMapping("/toadd")
    public String toadd() {
        return "edit";
    }

    @RequestMapping("/get")
    public String get(Integer nid, Model model) {

        model.addAttribute("news", newsService.getById(nid));
        return "edit";
    }

    @RequestMapping("/saveOrupdate")
    public String saveOrupdate(NewsSaveEntity news) {
        news.setNtid(1);
        news.setNauthor("admin");
        news.setNcreateDate(new Date());
        if (newsService.saveOrUpdate(news)) {

            SolrInputDocument inputDocument = new SolrInputDocument();
            inputDocument.addField("title", news.getNtitle());
            inputDocument.addField("id", news.getNid());

            UpdateResponse updateResponse = solrTemplate.saveBean("news_core",
                    inputDocument);
            System.out.println(updateResponse);
            solrTemplate.commit("news_core");
        }

        return "redirect:list";
    }
}
